package com.guigu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.mapper.*;
import com.guigu.pojo.*;
import com.guigu.service.GatherInfoService;
import com.guigu.service.utils.MyIdAdd;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class GatherInfoServiceimpl extends ServiceImpl<GatherInfoMapper, GatherInfo> implements GatherInfoService {
    @Autowired
    GatherInfoMapper gatherInfoMapper;//入库表
    @Autowired
    GatherDetailInfoMapper gatherDetailInfoMapper;//入库详情表
    @Autowired
    PurchaseInfoMapper purchaseInfoMapper;//采购表
    @Autowired
    PurchaseDetailInfoMapper purchaseDetailInfoMapper;//采购详情表
    @Autowired
    SupplierSupplyOfGoodsMapper supplierSupplyOfGoodsMapper;//商品维护表
    @Autowired
    WarehouseInfoMapper warehouseInfoMapper;//仓库表
    @Autowired
    WarehouseInfoServiceimpl warehouseInfoServiceimpl;//仓库表Service
    @Autowired
    WarehouseDetailsInfoMapper warehouseDetailsInfoMapper;//仓库详情表
    @Autowired
    ShopInfoMapper shopInfoMapper;//商品表
    @Autowired
    ReturnShopInfoMapper returnShopInfoMapper;//退货申请表
    @Autowired
    OrdersMapper ordersMapper;//订单表
    @Autowired
    OrdersParticularsMapper ordersParticularsMapper;//订单详情表
    @Autowired
    PayDetailInfoMapper payDetailInfoMapper;//出库详情表

    //根据采购单id，添加入库表和入库详情表数据，入库表需要审核
    @Override
    public Map addGatherInfoAndDetailPurchaseInfo(Integer id) {
        //根据采购单id，获取采购表对象和详情数据
        PurchaseInfo purchaseInfo=purchaseInfoMapper.selectById(id);
        QueryWrapper queryWrapper=new QueryWrapper<PurchaseDetailInfo>();
        queryWrapper.eq("pid",purchaseInfo.getId());
        purchaseInfo.setPurchaseDetails(purchaseDetailInfoMapper.selectList(queryWrapper));
        //入库对象
        GatherInfo gatherInfo=new GatherInfo();
        //采购理由：采购入库
        gatherInfo.setGatherType(0);
        //查询号：存放采购单
        gatherInfo.setTrackingNumber(purchaseInfo.getBuyNumber());
        //入库时间：当前时间
        gatherInfo.setGtime(new Date());
        //审核状态：等待审核
        gatherInfo.setIsCheck(0);
        //详情表是否全部指定了仓库：未全部指定
        gatherInfo.setAllSpecified(0);
        //删除状态：正常
        gatherInfo.setIsDelete(0);
        //进行添加
        Map map=new HashMap<String,Object>();
        if(gatherInfoMapper.insert(gatherInfo)>0){
            //循环采购详情表添加入库详情表数据
            for(PurchaseDetailInfo p : purchaseInfo.getPurchaseDetails()){
                GatherDetailInfo gatherDetailInfo=new GatherDetailInfo();
                gatherDetailInfo.setGatherId(gatherInfo.getId());
                gatherDetailInfo.setWarId(null);
                gatherDetailInfo.setSupplyOrderId(p.getSupplyOrderId());
                gatherDetailInfo.setShopNum(p.getShopNum());
                gatherDetailInfo.setIsDelete(0);
                //进行添加入库详情数据
                gatherDetailInfoMapper.insert(gatherDetailInfo);
            }
            //修改采购单的设计状态设置为已设计
            UpdateWrapper updateWrapper =new UpdateWrapper<PurchaseInfo>();
            updateWrapper.eq("id",purchaseInfo.getId());
            updateWrapper.set("is_design",1);
            purchaseInfoMapper.update(new PurchaseInfo(),updateWrapper);
            map.put("msg","开始对该采购单指定仓库");
            map.put("x",true);
        }else {
            map.put("msg","操作错误");
            map.put("x",false);
        }
        return map;
    }

    //根据采购详情id，获取可以存放的仓库有哪些
    @Override
    public com.guigu.service.utils.Page storableWarehouse(PurchaseDetailInfo purchaseDetailInfo, Integer pageno, Integer pagesize) {
        //筛选结果
        List<WarehouseInfo> result=new ArrayList<WarehouseInfo>();
        //补全属性
        purchaseDetailInfo=purchaseDetailInfoMapper.selectById(purchaseDetailInfo.getId());
        purchaseDetailInfo.setSupply(supplierSupplyOfGoodsMapper.selectById(purchaseDetailInfo.getSupplyOrderId()));
        //查询仓库
        QueryWrapper queryWrapper=new QueryWrapper<WarehouseInfo>();
        //审核通过
        queryWrapper.eq("is_check",1);
        //删除状态为正常
        queryWrapper.eq("is_delete",0);
        List<WarehouseInfo> warehouseInfoList=warehouseInfoMapper.selectList(queryWrapper);
        //循环仓库
        for(WarehouseInfo w :warehouseInfoList){
            //检查仓库下的详情数据是否满足该商品维护id
            queryWrapper=new QueryWrapper<WarehouseDetailsInfo>();
            queryWrapper.eq("p_id",w.getId());
            queryWrapper.eq("shop_id",purchaseDetailInfo.getSupply().getGId());
            queryWrapper.eq("is_check",1);//审核状态为通过
            //检查是否查询到数据
            WarehouseDetailsInfo temp_obj=warehouseDetailsInfoMapper.selectOne(queryWrapper);
            System.out.println("对象："+temp_obj);
            if(temp_obj!=null){
                //查询到数据，补全属性，并且将数据存入对象内，将仓库存入集合内
                //获取仓库的所剩总库存
                w.setRemnantInventory(warehouseInfoServiceimpl.calculateRemnantInventory(w));
                //计算该详情的最大存储数量-锁定库存是否满足本次采购详情想要存储的数量
                // 并且还要计算当前仓库的当前总存储量是否满足本次要存入的数量
                boolean x=(temp_obj.getMaxNum()-temp_obj.getLockStock())>=purchaseDetailInfo.getShopNum()
                        && (w.getRemnantInventory()-purchaseDetailInfo.getShopNum())>=0?true:false;
                //将判断结果存入对象属性内
                w.setIsDeposit(x);
                //商品对象
                temp_obj.setShopInfo(shopInfoMapper.selectById(temp_obj.getShopId()));
                List<WarehouseDetailsInfo> temp_list=new ArrayList<>();
                temp_list.add(temp_obj);
                w.setWarehouseDetailsInfoList(temp_list);
                result.add(w);
            }
        }
        com.guigu.service.utils.Page page=new com.guigu.service.utils.Page();
        return page.pageList(result,pageno,pagesize);
    }

    //最终提交
    @Override
    public Map changeDetailInfoState(Integer purchaseInfoId) {
        Map map=new HashMap<String,Object>();
        //根据采购单id，获取采购对象
        PurchaseInfo purchaseInfo=purchaseInfoMapper.selectById(purchaseInfoId);
        //发货状态修改已发起入库申请
        purchaseInfo.setIsShipments(3);
        purchaseInfoMapper.updateById(purchaseInfo);
        //根据采购表对象的采购单号，获取入库申请表
        QueryWrapper queryWrapper=new QueryWrapper<GatherInfo>();
        queryWrapper.eq("tracking_number",purchaseInfo.getBuyNumber());
        GatherInfo gatherInfo=gatherInfoMapper.selectOne(queryWrapper);
        //将全部指定状态属性修改为1
        gatherInfo.setAllSpecified(1);
        gatherInfoMapper.updateById(gatherInfo);
        map.put("msg","提交成功，等待审核");
        map.put("x",true);
        return map;
    }

    //分页查询
    @Override
    public Page<GatherInfo> queryAll(GatherInfo gatherInfo, Integer pageno, Integer pagesize) {
        QueryWrapper queryWrapper=
                new QueryWrapper<GatherInfo>();
        //查询号
        if (gatherInfo.getTrackingNumber()!=null){
            queryWrapper.eq("tracking_number",gatherInfo.getTrackingNumber());
        }
        //入库理由
        if (gatherInfo.getGatherType()!=null){
            queryWrapper.eq("gather_type",gatherInfo.getGatherType());
        }
        //审核状态
        if (gatherInfo.getIsCheck()!=null){
            queryWrapper.eq("is_check",gatherInfo.getIsCheck());
        }
        //是否全部指定仓库
        if (gatherInfo.getAllSpecified()!=null){
            queryWrapper.eq("all_specified",gatherInfo.getAllSpecified());
        }
        //删除状态
        if (gatherInfo.getIsDelete()!=null){
            queryWrapper.eq("is_delete",gatherInfo.getIsDelete());
        }
        Page<GatherInfo> page = this.page(new Page<GatherInfo>(pageno, pagesize),queryWrapper);
        for (GatherInfo g : page.getRecords()) {
            //获取详情表集合
            queryWrapper=new QueryWrapper<GatherDetailInfo>();
            queryWrapper.eq("gather_id",g.getId());
            g.setGatherDetailInfoList(gatherDetailInfoMapper.selectList(queryWrapper));
        }
        return page;
    }

    //审核入库单
    @Override
    public Map audit(GatherInfo gatherInfo) {
        Map map=new HashMap<String,Object>();
        //获取审核结果
        Integer result=gatherInfo.getIsCheck();
        //获取入库表对象
        gatherInfo=gatherInfoMapper.selectById(gatherInfo.getId());
        //获取入库详情数据
        QueryWrapper queryWrapper=new QueryWrapper<GatherDetailInfo>();
        queryWrapper.eq("gather_id",gatherInfo.getId());
        List<GatherDetailInfo> gatherDetailInfoList=gatherDetailInfoMapper.selectList(queryWrapper);
        //检查审核结果
        if(result==1){
            //允许通过
            //修改审核状态
            gatherInfo.setIsCheck(result);
            if(gatherInfoMapper.updateById(gatherInfo)>0){
                map.put("msg","审核通过");
                map.put("x",true);
            }else {
                map.put("msg","操作错误");
                map.put("x",false);
            }
            //循环入库详情，为每一个入库详情对应的仓库属性列的真实库存进行修改
            for(GatherDetailInfo g : gatherDetailInfoList){
                queryWrapper=new QueryWrapper<WarehouseDetailsInfo>();
                //获取商品维护表数据
                g.setSupplierSupplyOfGoods(supplierSupplyOfGoodsMapper.selectById(g.getSupplyOrderId()));
                queryWrapper.eq("p_id",g.getWarId());
                queryWrapper.eq("shop_id",g.getSupplierSupplyOfGoods().getGId());
                //查找仓库详情表
                WarehouseDetailsInfo warehouseDetailsInfo=warehouseDetailsInfoMapper.selectOne(queryWrapper);
                //根据仓库详情表数据，对真实库存进行修改
                //【真实库存=当前真实库存+入库详情的入库商品数量】
                warehouseDetailsInfo.setAmount(warehouseDetailsInfo.getAmount()+g.getShopNum());
                warehouseDetailsInfoMapper.updateById(warehouseDetailsInfo);
            }
            //检查查询号是否为退货单【采购单前缀编号为400】
            String trackingNumber_3=gatherInfo.getTrackingNumber().substring(0,3);
            System.out.println("截取获得的字符："+trackingNumber_3);
            if(trackingNumber_3.equals("400")){
                queryWrapper=new QueryWrapper<ReturnShopInfo>();
                queryWrapper.eq("return_number",gatherInfo.getTrackingNumber());
                //是退货单，获取退货单对象
                ReturnShopInfo returnShopInfo=returnShopInfoMapper.selectOne(queryWrapper);
                //修改退货单
                //货物状态设置为退货成功
                returnShopInfo.setGoodsState(8);
                returnShopInfoMapper.updateById(returnShopInfo);
                //获取订单详情对象
                OrdersParticulars ordersParticulars=ordersParticularsMapper.selectById(returnShopInfo.getOdId());
                //设置为退货完成
                ordersParticulars.setIsReturn(2);
                //修改订单详情
                ordersParticularsMapper.updateById(ordersParticulars);
                //获取订单详情,检查该订单详情下的是否为全部退货完成
                queryWrapper=new QueryWrapper<OrdersParticulars>();
                queryWrapper.eq("p_id",ordersParticulars.getPId());
                List<OrdersParticulars> ordersParticularsList=ordersParticularsMapper.selectList(queryWrapper);
                //循环检查是否都为全部退货完成
                int count=0;
                for(OrdersParticulars od:ordersParticularsList){
                    if(od.getIsReturn()==2){
                        count++;
                    }
                }
                if(count==ordersParticularsList.size()){
                    //说明全部退货,将订单状态修改为全部退货
                    Orders orders=ordersMapper.selectById(ordersParticulars.getPId());
                    orders.setOrderState("o-4");
                    ordersMapper.updateById(orders);
                }
            }
        }else {
            //拒绝通过
            //修改审核状态
            gatherInfo.setIsCheck(result);
            if(gatherInfoMapper.updateById(gatherInfo)>0){
                map.put("msg","拒绝通过");
                map.put("x",true);
            }else {
                map.put("msg","操作错误");
                map.put("x",false);
            }
            //循环入库详情，为每一个入库详情对应的仓库属性列的锁定库存进行修改
            for(GatherDetailInfo g : gatherDetailInfoList){
                queryWrapper=new QueryWrapper<WarehouseDetailsInfo>();
                //获取商品维护表数据
                g.setSupplierSupplyOfGoods(supplierSupplyOfGoodsMapper.selectById(g.getSupplyOrderId()));
                queryWrapper.eq("p_id",g.getWarId());
                queryWrapper.eq("shop_id",g.getSupplierSupplyOfGoods().getGId());
                //查找仓库详情表
                WarehouseDetailsInfo warehouseDetailsInfo=warehouseDetailsInfoMapper.selectOne(queryWrapper);
                //根据仓库详情表数据，对锁定库存进行修改
                //【锁定库存=当前锁定库存-入库详情的入库商品数量】
                warehouseDetailsInfo.setLockStock(warehouseDetailsInfo.getLockStock()-g.getShopNum());
                warehouseDetailsInfoMapper.updateById(warehouseDetailsInfo);
            }
            //根据入库申请表的查询号，获取采购单或者退货单对象
            //检查查询号是否为采购单【采购单前缀编号为200】
            String trackingNumber_3=gatherInfo.getTrackingNumber().substring(0,3);
            System.out.println("截取获得的字符："+trackingNumber_3);
            if(trackingNumber_3.equals("200")){
                //是采购单，获取采购单对象
                queryWrapper=new QueryWrapper<PurchaseInfo>();
                queryWrapper.eq("buy_number",gatherInfo.getTrackingNumber());
                PurchaseInfo purchaseInfo=purchaseInfoMapper.selectOne(queryWrapper);
                //修改采购单的是否全部设计状态设置为未设计
                purchaseInfo.setIsDesign(0);
                //修改采购单的设计状态设置为到达总店
                purchaseInfo.setIsShipments(2);
                purchaseInfoMapper.updateById(purchaseInfo);
                //获取采购单详情对象集合
                queryWrapper=new QueryWrapper<PurchaseDetailInfo>();
                queryWrapper.eq("pid",purchaseInfo.getId());
                List<PurchaseDetailInfo> purchaseDetailInfoList=purchaseDetailInfoMapper.selectList(queryWrapper);
                //循环采购单详情对象
                for(PurchaseDetailInfo p : purchaseDetailInfoList){
                    //将设计状态修改为未设计
                    p.setIsDesign(0);
                    purchaseDetailInfoMapper.updateById(p);
                }
            }else {
                //不是采购单，那么就是退货单，获取退货申请对象
                queryWrapper=new QueryWrapper<ReturnShopInfo>();
                queryWrapper.eq("return_number",gatherInfo.getTrackingNumber());
                ReturnShopInfo returnShopInfo=returnShopInfoMapper.selectOne(queryWrapper);
                //修改退货申请的设计状态修改为未设计
                returnShopInfo.setIsDesign(0);
                //货物状态设置为7:总店签收成功，等待总店入库
                returnShopInfo.setGoodsState(7);
                //修改退货申请表
                returnShopInfoMapper.updateById(returnShopInfo);
            }
        }
        System.out.println("审核结果："+result);
        return map;
    }
    //曹科 入库申请查询
    @Override
    public Page queryAllGatherInfo(GatherInfo gatherInfo, Integer pageno, Integer pagesize) {
        QueryWrapper<GatherInfo> queryWrapper=new QueryWrapper<GatherInfo>();
        queryWrapper.eq("is_delete","0");
        if(StringUtils.isNotEmpty(gatherInfo.getTrackingNumber())) {
            queryWrapper.eq("tracking_number", gatherInfo.getTrackingNumber());
        }
        return this.page(new Page<GatherInfo>(pageno,pagesize),queryWrapper);
    }

    //根据退货表id，获取可以存放的仓库有哪些
    @Override
    public com.guigu.service.utils.Page salesReturnWarehouse(ReturnShopInfo returnShopInfo, Integer pageno, Integer pagesize) {
        //筛选结果
        List<WarehouseInfo> result=new ArrayList<WarehouseInfo>();
        //补全属性
        returnShopInfo=returnShopInfoMapper.selectById(returnShopInfo.getId());;
        //获取订单详情id
        returnShopInfo.setDetail(ordersParticularsMapper.selectById(returnShopInfo.getOdId()));
        OrdersParticulars ordersParticulars=returnShopInfo.getDetail();
        //根据出库详情id，获取出库详情对象
        PayDetailInfo payDetailInfo=payDetailInfoMapper.selectById(ordersParticulars.getPdId());
        //获取商品维护对象
        SupplierSupplyOfGoods supplierSupplyOfGoods=supplierSupplyOfGoodsMapper.selectById(payDetailInfo.getSupplyOrderId());
        //查询仓库
        QueryWrapper queryWrapper=new QueryWrapper<WarehouseInfo>();
        //审核通过
        queryWrapper.eq("is_check",1);
        //删除状态为正常
        queryWrapper.eq("is_delete",0);
        List<WarehouseInfo> warehouseInfoList=warehouseInfoMapper.selectList(queryWrapper);
        //循环仓库
        for(WarehouseInfo w :warehouseInfoList){
            //检查仓库下的详情数据是否满足该商品维护id
            queryWrapper=new QueryWrapper<WarehouseDetailsInfo>();
            queryWrapper.eq("p_id",w.getId());
            queryWrapper.eq("shop_id",supplierSupplyOfGoods.getGId());
            queryWrapper.eq("is_check",1);//审核状态为通过
            //检查是否查询到数据
            WarehouseDetailsInfo temp_obj=warehouseDetailsInfoMapper.selectOne(queryWrapper);
            System.out.println("对象："+temp_obj);
            if(temp_obj!=null){
                //查询到数据，补全属性，并且将数据存入对象内，将仓库存入集合内
                //获取仓库的所剩总库存
                w.setRemnantInventory(warehouseInfoServiceimpl.calculateRemnantInventory(w));
                //计算该详情的最大存储数量-锁定库存是否满足本次采购详情想要存储的数量
                // 并且还要计算当前仓库的当前总存储量是否满足本次要存入的数量
                boolean x=(temp_obj.getMaxNum()-temp_obj.getLockStock())>=ordersParticulars.getBuyQuantity()
                        && (w.getRemnantInventory()-ordersParticulars.getBuyQuantity())>=0?true:false;
                //将判断结果存入对象属性内
                w.setIsDeposit(x);
                //商品对象
                temp_obj.setShopInfo(shopInfoMapper.selectById(temp_obj.getShopId()));
                List<WarehouseDetailsInfo> temp_list=new ArrayList<>();
                temp_list.add(temp_obj);
                w.setWarehouseDetailsInfoList(temp_list);
                result.add(w);
            }
        }
        com.guigu.service.utils.Page page=new com.guigu.service.utils.Page();
        return page.pageList(result,pageno,pagesize);
    }

    //根据退货申请表id和仓库名，添加入库表和入库详情表数据并且指定仓库，入库表需要审核
    @Override
    public Map addGatherInfoandSalesReturn(Integer id,Integer warehouseId) {
        //根据退货申请id，获取退货申请对象和订单详情对象
        ReturnShopInfo returnShopInfo=returnShopInfoMapper.selectById(id);
        returnShopInfo.setDetail(ordersParticularsMapper.selectById(returnShopInfo.getOdId()));
        //入库对象
        GatherInfo gatherInfo=new GatherInfo();
        //入库理由：退货入库
        gatherInfo.setGatherType(1);
        //查询号：存放退货申请编号
        gatherInfo.setTrackingNumber(returnShopInfo.getReturnNumber());
        //入库时间：当前时间
        gatherInfo.setGtime(new Date());
        //审核状态：等待审核
        gatherInfo.setIsCheck(0);
        //详情表是否全部指定了仓库：全部指定
        gatherInfo.setAllSpecified(1);
        //删除状态：正常
        gatherInfo.setIsDelete(0);
        //进行添加
        Map map=new HashMap<String,Object>();
        if(gatherInfoMapper.insert(gatherInfo)>0){
            //获取订单详情id
            OrdersParticulars ordersParticulars=returnShopInfo.getDetail();
            //根据出库详情id，获取出库详情对象
            PayDetailInfo payDetailInfo=payDetailInfoMapper.selectById(ordersParticulars.getPdId());
            //获取商品维护对象
            SupplierSupplyOfGoods supplierSupplyOfGoods=supplierSupplyOfGoodsMapper.selectById(payDetailInfo.getSupplyOrderId());
            //添加入库详情表数据
            GatherDetailInfo gatherDetailInfo=new GatherDetailInfo();
            gatherDetailInfo.setGatherId(gatherInfo.getId());
            gatherDetailInfo.setWarId(warehouseId);
            gatherDetailInfo.setSupplyOrderId(supplierSupplyOfGoods.getId());
            gatherDetailInfo.setShopNum(ordersParticulars.getBuyQuantity());
            gatherDetailInfo.setIsDelete(0);
            //进行添加入库详情数据
            gatherDetailInfoMapper.insert(gatherDetailInfo);
            //获取仓库对象
            WarehouseInfo warehouseInfo=warehouseInfoMapper.selectById(warehouseId);
            //获取仓库详情对象，进行条件筛选
            QueryWrapper queryWrapper=new QueryWrapper<WarehouseDetailsInfo>();
            queryWrapper.eq("p_id",warehouseInfo.getId());
            queryWrapper.eq("shop_id",supplierSupplyOfGoods.getGId());
            WarehouseDetailsInfo warehouseDetailsInfo=warehouseDetailsInfoMapper.selectOne(queryWrapper);
            //根据指定的仓库下的仓库详情的锁定库存进行增加
            warehouseDetailsInfo.setLockStock(warehouseDetailsInfo.getLockStock()+gatherDetailInfo.getShopNum());
            //修改仓库详情对象
            warehouseDetailsInfoMapper.updateById(warehouseDetailsInfo);

            //修改退货申请表的货物状态
            returnShopInfo.setGoodsState(11);//从7:总店签收成功，等待总店入库到11:退货申请中
            returnShopInfoMapper.updateById(returnShopInfo);
            map.put("msg","成功发起退货入库申请，等待审核");
            map.put("x",true);
        }else {
            map.put("msg","操作错误");
            map.put("x",false);
        }
        return map;
    }
}
